<template>
  <!--计划商品佣金设置组件 -->
  <div>
    <h4 class="title-layer-bar flex v-align-c">
      <div class="line"></div>
      <div>佣金设置</div>
    </h4>
    <div class="pad-t-10 mar-b-10">
      <el-button type="primary" @click="handleOpenSelectGoods">选择商品</el-button>
    </div>
    <!--顶部搜索 -->
    <div class="top-operate-default">
      <div class="search-item">
        <label class="font-14"></label>
        <el-select class="select-class" v-model="searchListQuery.keywordType" style="width: 120px">
          <el-option label="商品名称" value="1"></el-option>
          <el-option label="商品货号" value="2"></el-option>
        </el-select>
        <el-input @keyup.enter.native="handleSearch" v-model.trim="searchListQuery.keyword" placeholder="请输入关键词"
          style="width: 280px;">
        </el-input>
        <label class="font-14 mar-l-20">商品分类：</label>
        <el-cascader v-model="categoryIds" :props="{ checkStrictly: true }" change-on-select placeholder="选择商品分类"
          :options="categoryData" class="special-input" clearable>
        </el-cascader>
        <label class="font-14 mar-l-20">商品来源：</label>
        <el-select v-model="goodsSource" style="width: 120px">
          <el-option label="全部" value=""></el-option>
          <el-option v-for="(value, key) in dict.goodsSource" :key="key" :label="value" :value="key">
          </el-option>
          <el-option v-for="(item, index) in supplierList" :key="item.supplierId" :label="item.supplierName"
            :value="item.supplierId">
          </el-option>
        </el-select>
        <el-button-group class="mar-l-20">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetClick">重置</el-button>
        </el-button-group>
      </div>
    </div>
    <div class="mar-t-10">
      <div class="search-item">
        <el-checkbox class="mar-l-14 mar-r-0" v-model="allChecked" @change="handleSelectCurrentPage"><span
            class="mar-l-10 font-14">当页全选</span></el-checkbox>
        <span class="pad-l-4 pad-r-4">|</span>
        <span class="pad-r-4">合计已选商品{{multipleSelection.length}}项</span>
        <el-button @click="handleDelete()">批量移除</el-button>
        <el-input placeholder="请输入佣金比例" v-model="setAllCommissionRate" style="width: 220px;"
          @keyup.native="setAllCommissionRate = checkInputNum(setAllCommissionRate)">
          <template slot="append">%</template>
        </el-input>
        <el-button @click="handleSetAllCommissionRate">填充所有</el-button>
      </div>
    </div>
    <!-- 内容列表 -->
    <div class="table-container mar-t-10">
      <el-table ref="multipleTable" :element-loading-text="loadingText" style="width: 100%"
        header-cell-class-name="default-header" row-class-name="default-row" :data="goodsList" v-loading="listLoading"
        @selection-change="handleSelectionChange">
        <el-table-column width="50px" type="selection" fixed="left"></el-table-column>
        <el-table-column width="350px" label="商品信息" fixed="left">
          <template slot-scope="scope">
            <div class="flex v-align-c cursor-p mar-r-30">
              <label><img :src="scope.row.mainImage" class="user-avatar cursor-p width-70 height-70"></label>
              <div class="font-14 pad-l-10 v-align-h height-65">
                <div class="goods-title">
                  <div class="line-2">
                    {{scope.row.title}}
                  </div>
                </div>
                <template v-if="scope.row.categoryName">
                  <span class="font-color-6 font-13">[{{scope.row.categoryName}}]</span>
                </template>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column min-width="180px" label="货号">
          <template slot-scope="scope">
            {{scope.row.goodsCode}}
          </template>
        </el-table-column>
        <el-table-column min-width="110px" align="center" label="来源" prop="goodsNum">
          <template slot-scope="scope">
            <span v-if="scope.row.goodsSource !== 1">{{dict.goodsSource[scope.row.goodsSource]}}</span>
            <span v-if="scope.row.goodsSource == 1">{{scope.row.supplierName}}</span>
          </template>
        </el-table-column>
        <el-table-column width="150px" align="left" label="库存">
          <template slot-scope="scope">
            <div>
              <span>可用：</span>
              <el-button type="text" @click="seeStockDetail(scope.row)"
                :disabled="scope.row.goodsSource === 3 ? true:false">
                {{scope.row.remainStock}}
              </el-button>
            </div>
            <div>
              <span>占用：</span>
              <el-button type="text" @click="seeStockDetail(scope.row)"
                :disabled="scope.row.goodsSource === 3 ? true:false">
                {{scope.row.stockInUse}}
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column min-width="140px" align="center" label="样品价">
          <template slot-scope="scope">
            ￥{{scope.row.specimenPrice}}
          </template>
        </el-table-column>
        <el-table-column min-width="140px" align="center" label="零售价">
          <template slot-scope="scope">
            ￥{{scope.row.sellPrice}}
          </template>
        </el-table-column>
        <el-table-column min-width="140px" align="center" label="推广佣金">
          <template slot-scope="scope">
            <el-input placeholder="请输入佣金" v-model="scope.row.commissionRate" @blur="saveCommissionRate(scope.row)"
              @keyup.native="scope.row.commissionRate = checkInputNum(scope.row.commissionRate)">
              <template slot="append">%</template>
            </el-input>
          </template>
        </el-table-column>
        <el-table-column width="140px" label="操作" align="right" fixed="right">
          <template slot-scope="scope">
            <el-popconfirm title="确定要删除吗？" @onConfirm="handleDelete(scope.row)">
              <el-button type="text" size="medium" slot="reference">移除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 列表分页 -->
    <pagination v-show="total>0" :total="total" :page.sync="searchListQuery.currentPage"
      :limit.sync="searchListQuery.size" @pagination="getPlanGoodsList" />

    <!-- 选择商品组件 -->
    <plan-select-goods :onSureCall="handleSureSuccessCall" ref="planSelectGoodsRef"></plan-select-goods>

    <!-- 商品库存详情dialog -->
    <el-dialog title="商品库存详情" :visible.sync="openStockDetail" :center="true" top="5vh" width="850px">
      <goods-stock-detail :showFlag="openStockDetail" :goodsObj="selectGoodsObj" @callback="openStockDetail = false">
      </goods-stock-detail>
    </el-dialog>
  </div>
</template>


<script>
  import elDragDialog from '@/directive/el-dragDialog' // base on element-ui
  import goodsStockDetail from '@/views/goods/components/goods-stock-detail'
  import planSelectGoods from '../plan-select-goods'
  import {
    getDictByGroupName
  } from '@/api/common/common'
  import {
    listGoodsCategory
  } from '@/api/goods/goods'
  import {
    listSupplier
  } from '@/api/user/supplier'
  import {
    pagePlanGoodsRelationList,
    deleteBatchPlanGoodsRelation,
    savePlanGoodsRelation,
    batchSavePlanGoodsRelationByGoodsIds,
    updatePlanGoodsCommissionRateByPlanId
  } from '@/api/user/enterprisePlanManagement'
  import {
    getByEnterpriseId
  } from '@/api/user/enterprise'
  export default {
    components: {
      goodsStockDetail,
      planSelectGoods
    },
    directives: {
      elDragDialog
    },
    data() {
      return {
        listLoading: false,
        loadingText: '加载中',
        total: 0,
        goodsList: [],
        goodsSource: '',
        searchListQuery: {
          keywordType: '1',
          keyword: '',
          currentPage: 1,
          size: 10,
          selectionGoodsType: 1
        },
        multipleSelection: [],
        categoryIds: [],
        // 商品的所有分类json
        categoryData: [],
        // 供应商数据
        supplierList: [],
        dict: {},
        // 设置所有商品的佣金比例值
        setAllCommissionRate: '',
        planForm: {

        },
        selectGoodsObj: {},
        openStockDetail: false,
        rules: {},
        // 企业配置信息
        enterpriseConfig: {
          warehouseDeliverFlag: 0
        },
        allChecked: false
      }
    },
    // 初始化页面
    created() {
      getByEnterpriseId(this.getEnterpriseId()).then(response => {
        if (response.isError) return
        this.enterpriseConfig = response.data
      })
      this.initDict()
      this.listSupplier()
      this.listGoodsCategory()

      const that = this
      that.$bus.$on('plan.data', function(data) {
        Object.assign(that.planForm, data)
        // 加载计划商品列表
        that.getPlanGoodsList()
      })
    },
    methods: {
      // 获取商品数据
      getPlanGoodsList() {
        if (this.planForm.planId) {
          this.listLoading = true
          this.loadingText = '加载中'
          this.searchListQuery.planId = this.planForm.planId
          this.searchListQuery.enterpriseId = this.getEnterpriseId()
          if (this.categoryIds.length > 0) {
            this.searchListQuery.searchCategoryId = this.categoryIds[this.categoryIds.length - 1]
          }
          if (this.goodsSource !== '0' && this.goodsSource !== '1' && this.goodsSource !== '2' && this.goodsSource !==
            '3') {
            this.searchListQuery.supplierId = this.goodsSource
            this.searchListQuery.goodsSource = null
          } else {
            this.searchListQuery.supplierId = null
            this.searchListQuery.goodsSource = this.goodsSource
          }
          pagePlanGoodsRelationList(this.searchListQuery).then(response => {
            this.listLoading = false
            if (response.isError) return
            this.total = response.data.total
            var dataGoodsList = response.data.records

            this.goodsList = dataGoodsList
          })
        }
      },
      // 获取供应商列表
      listSupplier() {
        listSupplier({
          enterpriseId: this.getEnterpriseId()
        }).then(response => {
          if (response.isError) return
          this.supplierList = response.data
        })
      },
      // 获取类目
      listGoodsCategory() {
        const enterpriseId = this.getEnterpriseId()
        listGoodsCategory(enterpriseId).then(response => {
          this.categoryData = response.data
        })
      },
      // 获取数据字典
      initDict() {
        getDictByGroupName('ProjectGoodsDTO').then(response => {
          Object.assign(this.dict, response.data)
        })
      },
      handleSearch() {
        this.searchListQuery.currentPage = 1
        this.getPlanGoodsList()
      },
      resetClick() {
        const originData = this.$options.data()
        this.searchListQuery = originData.searchListQuery
        this.categoryIds = []
        this.goodsSource = ''
        this.handleSearch()
      },
      // 勾选
      handleSelectionChange(val) {
        this.multipleSelection = val
        if (this.multipleSelection.length > 0 && this.multipleSelection.length === this.goodsList.length) {
          this.allChecked = true
        } else {
          this.allChecked = false
        }
      },
      // 选中当前页
      handleSelectCurrentPage() {
        if (this.multipleSelection.length === 0 || this.multipleSelection.length < this.goodsList.length) {
          this.goodsList.forEach(item => {
            this.$refs.multipleTable.toggleRowSelection(item, true)
          })
        } else {
          this.$refs.multipleTable.clearSelection()
        }
      },
      // 删除商品
      handleDelete(row) {
        var relationIds = []
        if (row) {
          relationIds.push(row.relationId)
          this.handleDeleteMethod(relationIds)
        } else {
          if (this.multipleSelection.length === 0) {
            this.msgError('请选择要删除的数据!')
            return
          }
          relationIds = this.multipleSelection.map(item => item.relationId)
          this.$confirm('确定要删除商品吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.handleDeleteMethod(relationIds)
          }).catch(() => {})
        }
      },
      // 删除
      handleDeleteMethod(relationIds) {
        this.listLoading = true
        this.loadingText = '删除中'
        deleteBatchPlanGoodsRelation(relationIds).then(response => {
          this.listLoading = false
          if (response.isError) return
          this.msgSuccess(response.msg)
          this.getPlanGoodsList()
        })
      },
      // 设置所有商品佣金比例
      handleSetAllCommissionRate() {
        if (this.planForm.planId) {
          if (!this.setAllCommissionRate) {
            this.msgError('请填写佣金比例')
            return
          }
          if (parseFloat(this.setAllCommissionRate) < 0 || parseFloat(this.setAllCommissionRate) > 100) {
            this.msgError('佣金比例范围为：0-100之间')
            return
          }
          this.$confirm('确定要设置所有商品佣金比例吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.listLoading = true
            this.loadingText = '修改中'
            updatePlanGoodsCommissionRateByPlanId(this.planForm.planId, this.setAllCommissionRate).then(
              response => {
                this.listLoading = false
                if (response.isError) return
                this.msgSuccess(response.msg)
                this.getPlanGoodsList()
              })
          }).catch(() => {})
        }
      },
      // 保存商品佣金比例
      saveCommissionRate(row) {
        if (!row.commissionRate) {
          row.commissionRate = 0
        }
        if (parseFloat(row.commissionRate) < 0 || parseFloat(row.commissionRate) > 100) {
          this.msgError('佣金比例范围为：0-100之间')
          return
        }
        savePlanGoodsRelation(row).then(response => {
          if (response.isError) {
            this.msgError(response.msg)
          }
        })
      },
      // 查看库存明细
      seeStockDetail(row) {
        this.selectGoodsObj = row
        this.openStockDetail = true
      },
      // 打开选择商品弹窗
      handleOpenSelectGoods() {
        this.$refs.planSelectGoodsRef.open(this.planForm.planId)
      },
      // 选择商品后的回调函数
      // selectGoodsType:1-选择当前所有，2-指定了商品，3-选择搜索结果，这里拿到的是商品id集合
      handleSureSuccessCall(selectGoodsType, row) {
        var goodsIds = []
        if (selectGoodsType === 2) {
          if (!row || row.length <= 0) {
            this.msgError('请选择商品!')
            return
          }
          goodsIds = row.map(item => item.goodsId)
        } else if (selectGoodsType === 3) {
          if (!row || row.length <= 0) {
            this.msgError('请选择商品!')
            return
          }
          goodsIds = row
        }

        const entity = {
          enterpriseId: this.getEnterpriseId(),
          planId: this.planForm.planId,
          savePlanGoodsRelationType: selectGoodsType,
          goodsIds: goodsIds
        }
        this.listLoading = true
        this.loadingText = '保存中'
        batchSavePlanGoodsRelationByGoodsIds(entity).then(response => {
          this.listLoading = false
          if (response.isError) return
          this.msgSuccess(response.msg)
          this.getPlanGoodsList()
        })
      }
    }
  }
</script>

<style lang="less" scoped>
  .pro-p-minheight {
    min-height: 148px;
  }

  .noraml-hide {
    display: none !important;
  }

  .active {
    display: block !important;
  }

  .span-bar {
    padding: 0 50px;
  }

  .remove-btn {
    padding: 7px 6px !important;
  }

  .long-input {
    width: 80%;
  }

  .long-input-2 {
    min-width: 55%;
    // margin-right: 10px;
  }

  .long-input-3 {
    width: 55%;
  }

  .short-input {
    width: 20%;
  }

  .short-input-2 {
    width: 25%;
  }

  .default-input {
    width: 50%;
  }

  .tips {
    color: gray;
    font-size: 12px;
    line-height: 1.2;
    padding-top: 5px;
  }

  .picture {
    width: 148px;
    height: 148px;
    display: block;
  }

  .pic-bar {
    position: relative;
    display: inline-block;

    .close-icon {
      position: absolute;
      right: -30px;
      top: -11px;
      width: 31px;
      height: 40px;
      padding: 0 7px;
      cursor: pointer;
    }

    span {
      position: absolute;
      right: 0;
      bottom: 0;
      width: 100%;
      display: block;
      color: #fff;
      text-align: center;
      padding: 3px 0;
      background: rgba(0, 0, 0, 0.5);
      cursor: pointer;
    }
  }

  .pic-add {
    background: #fff;
    border: #d3d3d3 1px dashed;
    border-radius: 5px;
    padding: 0 45px;
  }

  .el-dialog-div {
    height: 70vh;
    overflow: auto;
  }
</style>
